<template>
  <div class="publish">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: 'hello' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">文章管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>文章管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card"
             style='margin-top:20px'>
      <el-form ref="form"
               :model="post"
               label-width="80px"
               :rules="rules">
        <!-- 标题 -->
        <el-form-item label="标题"
                      prop='title'>
          <el-input v-model="post.title"></el-input>
        </el-form-item>
        <!-- 类型 -->
        <el-form-item label="类型">
          <el-radio-group v-model="post.type">
            <el-radio :label="1">文章</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 内容 -->
        <el-form-item label="类型">
          <!-- 富文本框 -->
          <VueEditor :config="config"
                     v-if='post.type==1'
                     ref="vueEditor" />
          <!-- 视频文件上传 -->
          <el-upload class="upload-demo"
                     action="http://localhost:3000/upload"
                     :headers='getToken()'
                     :on-success='onSuccess'
                     :file-list="fileList"
                     v-if='post.type==2'>
            <el-button size="small"
                       type="primary">点击上传</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传视频文件</div>
          </el-upload>
        </el-form-item>
        <!-- 栏目 -->
        <el-form-item label="栏目">
          <el-checkbox :indeterminate="isIndeterminate"
                       v-model="checkAll"
                       @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="cates"
                             @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item in cateList"
                         :label="item.id"
                         :key="item.id">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 封面 -->
        <el-form-item label="封面">
          <el-upload action="http://localhost:3000/upload"
                     :headers='getToken()'
                     :on-success='coverSuccess'
                     :on-remove='coverRemove'
                     list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-button type="primary"
                   @click='publish'>文章发布</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import VueEditor from "vue-word-editor";
import "quill/dist/quill.snow.css"
import { getCateList } from '@/apis/category.js'
import { publishPost } from '@/apis/post.js'

export default {
  components: {
    VueEditor
  },
  data () {
    return {
      isIndeterminate: false,
      checkAll: false,
      cates: [],
      cateList: [],


      fileList: [],
      post: {
        title: '',
        content: '',
        categories: [],
        cover: [],
        type: 1
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ]
      },
      config: {
        // 上传图片的配置
        uploadImage: {
          url: "http://localhost:3000/upload", // 上传文件的服务器处理地址
          name: "file",// 后台接口所需要的参数名称
          // 添加token的传递,插件本身有异步操作，不会经过我们所添加的拦截器
          headers: this.getToken(),
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess (res, insert) {
            console.log(res);
            insert("http://localhost:3000" + res.data.data.url)
          }
        },

        // 上传视频的配置
        uploadVideo: {
          url: "http://localhost:3000/upload",
          name: "file",
          // 添加token的传递
          headers: this.getToken(),
          uploadSuccess (res, insert) {
            insert("http://localhost:3000" + res.data.data.url)
          }
        }
      }
    }
  },
  async mounted () {
    let res = await getCateList()
    // 关注 和 头条 不参与用户交互
    this.cateList = res.data.data.slice(2)
    console.log(this.cateList);

  },
  methods: {
    handleCheckAllChange (val) {
      // cates数组中的值决定了那些复选框被选中，它是的id数组(里面的每个值都是id)
      // 所以，所谓全选功能的实现就是给它一个数组包含所有栏目数据的id,全不选就给它一个空值数组
      this.cates = val ? this.cateList.map(v => {
        return v.id
      }) : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange (value) {
      console.log(value);
      let checkedCount = value.length; // 获取选中的复选框的数量
      // 设置全选状态
      this.checkAll = checkedCount === this.cateList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cateList.length;
    },
    // 移除封面
    // file:当前被移除的文件
    // fileList：当前保留的文件列表
    coverRemove (file, fileList) {
      console.log(file, '---', fileList);
      let id = file.response.data.id
      // 将这个id所对应的数据从cover数组中删除
      for (let i = 0; i < this.post.cover.length; i++) {
        if (this.post.cover[i].id == id) { // 找到了
          this.post.cover.splice(i, 1)
          break
        }
      }
    },
    // 封面上传成功
    coverSuccess (response, file, fileList) {
      // console.log(response, file, fileList);
      if (response.message == "文件上传成功") {
        // 存储的值一定要参照后台接口
        this.post.cover.push({ id: response.data.id })
      }
    },
    // 内容块视频文件上传成功之后的触发函数
    onSuccess (response) {
      if (response.message == "文件上传成功") {
        this.post.content = response.data.url
      }
    },
    getToken () {
      return { Authorization: localStorage.getItem('heima_back_token_59') }
    },
    async publish () {
      // 如果是文章，就获取富文本框的数据
      if (this.post.type == 1) {
        this.post.content = this.$refs.vueEditor.editor.root.innerHTML
      }
      // 改造categories
      this.post.categories = this.cates.map(v => {
        return { id: v }
      })

      console.log(this.post);
      let res = await publishPost(this.post)
      console.log(res);
      if (res.data.message == "文章发布成功") {
        this.$message({
          type: 'success',
          message: '文章发布成功'
        })
        this.$router.push({ path: 'postlist' })
      }

    }
  }
}
</script>

<style>
</style>